<?php
/**
 * Created by PhpStorm.
 * Date: 2018/4/10
 * Time: 11:26
 */

namespace Et;

use FastRoute\RouteCollector;
use FastRoute\Dispatcher\GroupCountBased;
use FastRoute\DataGenerator\GroupCountBased as DataBased;
use Etong\Route;
use FastRoute\RouteParser\Std;
class Dispatch {

    protected $controllerNamespace = "";

    /**
     * 默认控制器的命名空间
     * Dispatch constructor.
     *
     * @param string $controllerNamespace
     */
    public function __construct ($controllerNamespace = 'app\\controller\\')
    {
        $this->controllerNamespace = $controllerNamespace;
    }

    /**
     * 路由调度
     *
     * @param \swoole_http_request  $request
     * @param \swoole_http_response $response
     */
    public function dispatch(\swoole_http_request $request,\swoole_http_response $response)
    {
        $routeList = Route::all();

        $dispatcher =  \FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $route) use($routeList){
            foreach ($routeList as $key=>$value) {
                $route->addRoute($value[0],$value[1],$value[2]);
            }
        });

        $method = $request->server['request_method'];
        $uri    = $request->server['request_uri'];
        $routeInfo = $dispatcher->dispatch($method, $uri);
        switch ($routeInfo[0]) {
            case \FastRoute\Dispatcher::NOT_FOUND:
                $response->status(404);
                $response->end("error:");
                break;
            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                break;
            case \FastRoute\Dispatcher::FOUND:

                $handler = $routeInfo[1];
                $vars = $routeInfo[2];
                if(is_callable($handler)) {
                    $a = $handler();
                    $response->write($a);
                    return ;
                }
                echo $handler.PHP_EOL;
                $defaultAction = 'index';
                //解析控制器 indexController@index
                if(is_string($handler)) {
                    if(strpos('@',$handler) === false ) {
                        $handler = $handler."@".$defaultAction;
                    }
                }
                $data = explode('@',$handler);
                $controller = $data[0];
                $action = $data[1];
                $this->controllerHandle($controller,$action);
                $response->end($controller);
                break;
        }

    }


    protected function controllerHandle($controller,$action='index')
    {
        if(empty($controller)) {
            return false;
        }

    }

}